package com.example.helloredis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author 12071
 * @date 2022/8/4 16:44
 */
@RestController
@RequestMapping("/redis")
public class redisController {

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/add")
    public String add(@RequestParam("key") String key, @RequestParam("value") String value){
        redisTemplate.opsForValue().set(key,value);
        return (String) redisTemplate.opsForValue().get(key);
    }

    @PostMapping("/expire")
    public String addWithExpired(@RequestParam("key") String key,
                      @RequestParam("value") String value,
                      @RequestParam("expireTime") Long expireTime){
        redisTemplate.opsForValue().set(key,value,expireTime, TimeUnit.MILLISECONDS);
        return (String) redisTemplate.opsForValue().get(key);
    }

    @GetMapping("/get")
    public String get(@RequestParam("key") String key){
        Object o = redisTemplate.opsForValue().get(key);
        return o != null ? o.toString() : "null";
    }

    @GetMapping("/has")
    public String has(@RequestParam("key") String key){
        return redisTemplate.hasKey(key).toString();
    }
}
